package org.top.rushpeak.edu03.core.generator;

import java.util.ArrayList;
import java.util.List;

public class EasyUiAndBootstrapGenerator {

	public static String HTML = "";
	
	private static void makeSearchDiv(Core core, List<Item> itemList) {

		String div = "<div id=\"p1\" class=\"easyui-panel\" title=\"查询\""
		+"style=\"padding: 10px; background: #fafafa; margin-bottom: 10px;\""
		+"iconCls=\"icon-sum\" closable=\"false\" collapsible=\"false\" minimizable=\"false\""
		+"maximizable=\"false\">";
		for(Item item:itemList){
			if(item.getIsSearch()==1){
				if(item.getType()==1||item.getType()==3){
					div+=item.getRealName()+":<input id=\""+item.getBeanName()+"\" name=\""+item.getBeanName()+"\" class=\"txt_fm_mmp easyui-validatebox search\">";
				}else if(item.getType()==2){
					div+=item.getRealName()+"from&nbsp;<input class=\"easyui-datebox \" name=\"startTime\"   id=\"startTime\""
							+"data-options=\"required:false,showSeconds:true\"  style=\"width:150px\">"
							+"to&nbsp;<input class=\"easyui-datebox\" name=\"endTime\"   id=\"endTime\""
							+"data-options=\"required:false,showSeconds:true\"  style=\"width:150px\">";
				}
			}
		}
		div+="<a href=\"javascript:search();\" class=\"easyui-linkbutton\" plain=\"true\""
			+"iconCls=\"icon-search\">搜索</a>"
			+"</div>";
		
		HTML += div;
	}

	private static void initCore(Core core) {
		HTML = HTML.replace("{part_main_ready_url}", core.getLag());
		HTML = HTML.replace("{part_main_ready_title}", core.getLagCN());
		
	}

	private static void makeTable(Core core, List<Item> itemList) {
		String div = ""
			+"<div class=\"modal fade\" id=\"myModal\" tabindex=\"-1\" role=\"dialog\""
			+"aria-labelledby=\"myModalLabel\" data-backdrop=\"false\">"
			+"<div class=\"modal-dialog\" role=\"document\">"
					+"<div class=\"modal-content\">"
						+"<div class=\"modal-header\">"
							+"<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">"
								+"<span aria-hidden=\"true\">&times;</span>"
							+"</button>"
							+"<h4 class=\"modal-title\" id=\"myModalLabel\">新增</h4>"
						+"</div>"
						+"<div class=\"modal-body\">"
							+"<form class=\"form-horizontal\">"
								+"<div class=\"form-group\" style=\"display: none\" id=\"showAddId\">"
									+"<label for=\"add_id\" class=\"col-sm-2 control-label\">id</label>"
									+"<div class=\"col-sm-10\">"
										+"<input type=\"text\" class=\"form-control\" id=\"add_id\" placeholder=\"ID\""
											+"readonly>"
											+"</div>"
								+"</div>";
		for(Item item:itemList){
			if(item.getType()==1&&!"id".equals(item.getBeanName())){
				div+="<div class=\"form-group\">"
						+"<label for=\"add_"+item.getBeanName()+"\" class=\"col-sm-2 control-label\">"+item.getRealName()+"</label>"
						+"<div class=\"col-sm-10\">"
							+"<input type=\"text\" class=\"form-control\" id=\"add_"+item.getBeanName()+"\" placeholder=\""+item.getRealName()+"\""
								+"required>"
								+"</div>"
					+"</div>";
			}
			if(item.getType()==2){
				div+="<div class=\"form-group\">"
						+"<label for=\"add_"+item.getBeanName()+"\" class=\"col-sm-2 control-label\""
								+"class=\"easyui-datebox\">"+item.getRealName()+"</label>"
								+"<div class=\"col-sm-10\">"
								+"<input class=\"easyui-datetimebox form-control\" name=\"add_"+item.getBeanName()+"\""
										+"id=\"add_"+item.getBeanName()+"\" data-options=\"required:false,showSeconds:true\""
												+"style=\"width: 150px\">"
												+"</div>"
					+"</div>";
			}
			if(item.getType()==3){
				div+="<div class=\"form-group\">"
						+"<label class=\"col-sm-2 control-label\">"+item.getRealName()+"</label>"
						+"<div class=\"col-sm-10\">"
							+"<select class=\"form-control\" id=\"add_"+item.getBeanName()+"\" required>"
								+"<option value=\"1\">是</option>"
								+"<option value=\"0\">否</option>"
							+"</select>"
						+"</div>"
					+"</div>";
			}
		}
		div+="</form>"
					+"</div>"
					+"<div class=\"modal-footer\">"
					+"<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>"
						+"<button type=\"button\" class=\"btn btn-primary addSubmitBtn\">提交</button>"
					+"</div>"
				+"</div>"
			+"</div>"
		+"</div>";
		
		HTML += div;
		initCore(core);
	}

	private static void makeFunction(Core core, List<Item> itemList) {
		String function = Source.PART_FUNCTION_REFRESH;
		if(core.getDoAdd()==1){
			String add= Source.PART_FUNCTION_ADD;
			String param = "";
			for(Item item: itemList){
				if(item.getType()==1||item.getType()==3){
					param += "$(\"#add_"+item.getBeanName()+"\").val(\"\");";					
				}else if(item.getType()==2){
					param += "$(\"#add_"+item.getBeanName()+"\").datebox('setValue', '');";
				}else{
					throw new RuntimeException("TYPE_ERR:"+item.getType());
				}
			}
			add = add.replace("{PART_FUNCTION_ADD_ITEMS}", param);
			function += add;
		}
		if(core.getDoUpdate()==1){
			String update= Source.PART_FUNCTION_UPDATE;
			String param = "";
			for(Item item: itemList){
				if(item.getType()==1||item.getType()==3){
					param += "$(\"#add_"+item.getBeanName()+"\").val(data.data."+item.getBeanName()+");";					
				}else if(item.getType()==2){
					param += "$(\"#add_"+item.getBeanName()+"\").datebox('setValue', 'data.data."+item.getBeanName()+"');";
				}else{
					throw new RuntimeException("TYPE_ERR:"+item.getType());
				}
			}
			update = update.replace("{PART_FUNCTION_UPDATE_ITEMS}", param);
			function += update;
		}
		if(core.getDoAdd()==1||core.getDoUpdate()==1){
			String submit = Source.PART_FUNCTION_ADD_COMMIT;
			String param = "";
			for(Item item:itemList){
				if(item.getType()==1||item.getType()==3){
					param += "req_params."+item.getBeanName()+" = $(\"#add_"+item.getBeanName()+"\").val();";					
				}else if(item.getType()==2){
					param += "req_params."+item.getBeanName()+" = $(\"#add_"+item.getBeanName()+"\").datebox('getValue')";
				}else{
					throw new RuntimeException("TYPE_ERR:"+item.getType());
				}
			}
			submit = submit.replace("{PART_FUNCTION_COMMIT_ITEMS}", param);
			function += submit;
		}
		if(core.getDoDel()==1){
			function += Source.PART_FUNCTION_DEL;
		}
		
		//搜索
		function += Source.PART_FUNCTION_SEARCH;
		String search1 = "";
		String search2 = "";
		for(Item item:itemList){
			if(item.getIsSearch()==1){
				search1+="var "+item.getBeanName()+"=$('#search_"+item.getBeanName()+"').val();";					
				search2+=item.getBeanName()+":"+item.getBeanName()+",";
			}
		}
		function.replace("{PART_FUNCTION_SEARCH_ITEM1}", search1);
		function.replace("{PART_FUNCTION_SEARCH_ITEM2}", search2);
		HTML = HTML.replace("{part_two_function}", function);
		initCore(core);
		
	}

	private static void makeMainReady(Core core, List<Item> itemList) {
		
		String mainReady = Source.PART_MAIN_READY;
		
		//TOOLBAR
		String toolBar = makeToolBar(core);
		mainReady = mainReady.replace("{part_main_ready_toolbar}", toolBar);
		
		mainReady = mainReady.replace("{part_main_ready_url}", core.getLag());
		mainReady = mainReady.replace("{part_main_ready_title}", core.getLagCN());
		
		String click = "";
		if(core.getDoAdd()==1){
			click += "$(document).on(\"click\", \".addSubmitBtn\", addSubmit);";
		}
		if(core.getDoUpdate()==1){
			click += "$(document).on(\"click\", \".updateBtn\", update);";
		}
		if(core.getDoDel()==1){
			click += "$(document).on(\"click\", \".delBtn\", deleteItem);";
		}
		mainReady = mainReady.replace("{part_main_ready_click}", click);
		
		String list = "";
		boolean isFirst = true;
		for(Item item:itemList){
			if(isFirst){
				isFirst = false;
			}else{
				list += ",";
			}
			
			switch (item.getType()) {
			case 1:
				list += Source.PART_MAIN_READY_LIST_NORMAL;
				list = list.replace("{part_main_ready_items_field}", item.getBeanName());
				list = list.replace("{part_main_ready_items_title}", item.getRealName());
				list = list.replace("{part_main_ready_items_width}", item.getWidth()+"");
				break;
			case 2:
				list += Source.PART_MAIN_READY_LIST_DATE;
				list = list.replace("{part_main_ready_items_field}", item.getBeanName());
				list = list.replace("{part_main_ready_items_title}", item.getRealName());
				list = list.replace("{part_main_ready_items_width}", item.getWidth()+"");
				break;
			case 3:
				list += Source.PART_MAIN_READY_LIST_BOOLEAN;
				list = list.replace("{part_main_ready_items_field}", item.getBeanName());
				list = list.replace("{part_main_ready_items_title}", item.getRealName());
				list = list.replace("{part_main_ready_items_width}", item.getWidth()+"");
				break;

			default:
				break;
			}
			
		}
		String action = ","+Source.PART_MAIN_READY_LIST_ACTION;
		if(core.getDoUpdate()==1&&core.getDoDel()==1){
			action = action.replace("{part_main_ready_items_action}", "a+b");				
		}else if(core.getDoUpdate()==1&&core.getDoDel()==0){
			action = action.replace("{part_main_ready_items_action}", "a");
		}else if(core.getDoUpdate()==0&&core.getDoDel()==1){
			action = action.replace("{part_main_ready_items_action}", "b");
		}else{
			action = "";
		}
		list += action;
		mainReady = mainReady.replace("{part_main_ready_items}", list);
		String two = Source.PART_TWO;
		two = two.replace("{part_two_content}", mainReady);
		HTML += two;
		
		initCore(core);
		
	}

	public static String makeToolBar(Core core){
		String toolBar = Source.PART_TOOL_BAR_MAIN;
		String main = "";
		main += Source.PART_TOOL_BAR_REFRESH;
		if(core.getDoAdd()==1){
			main += Source.PART_TOOL_BAR_CONNECT;
			main += Source.PART_TOOL_BAR_ADD;
		}
		
		toolBar = toolBar.replace("{part_tool_bar_content}", main);
		initCore(core);
		return toolBar;
	}
	
	public static void main(String[] args) {

		List<Item> itemList = new ArrayList<>();
		itemList.add(new Item("id", "ID",50, 1, 1, 1));
		itemList.add(new Item("name", "任务名",100, 1, 1, 1));
		itemList.add(new Item("group", "任务组名",100, 1, 1, 1));
		itemList.add(new Item("class", "类全名",200, 1, 1, 0));
		itemList.add(new Item("cron_expression", "定时表达式",100, 1, 1, 0));
		itemList.add(new Item("is_enabled", "是否启动",100, 3, 1, 1));
//		itemList.add(new Item("groupId", "优惠券组ID",100, 1, 1, 1));
//		itemList.add(new Item("userId", "用户ID",100, 1, 1, 1));
//		itemList.add(new Item("cardNumber", "优惠券编码",100, 1, 1, 0));
//		itemList.add(new Item("isUse", "ID",50, 3, 1, 1));
//		itemList.add(new Item("couponGroupId", "优惠券组ID",150, 1, 1, 0));
//		itemList.add(new Item("remark", "标题",150, 1, 1, 0));
//		itemList.add(new Item("type", "类别",150, 3, 1, 0));
//		itemList.add(new Item("startTime", "开始时间",150, 2, 1, 0));
//		itemList.add(new Item("endTime", "结束时间",150, 2, 1, 0));
//		itemList.add(new Item("createTime", "创建时间",150, 2, 1, 0));
		
		
		Core core = new Core(1, 1, 1, "jobmanage","任务调度");

		HTML += Source.PART_ONE;
		makeMainReady(core,itemList);
		
		makeFunction(core,itemList);

		HTML+="<table id=\"datagrid\"></table>";
		
		makeSearchDiv(core,itemList);
		
		makeTable(core,itemList);
		
		initCore(core);
		
		System.out.println(HTML);
	}

}

class Source {

	public static String PART_ONE;
	public static String PART_TWO;

	public static String PART_MAIN_READY;
	public static String PART_MAIN_READY_LIST_NORMAL;
	public static String PART_MAIN_READY_LIST_DATE;
	public static String PART_MAIN_READY_LIST_BOOLEAN;
	public static String PART_MAIN_READY_LIST_ACTION;
	
	public static String PART_DATE_TYPE;
	
	public static String PART_TOOL_BAR_MAIN;
	public static String PART_TOOL_BAR_CONNECT;
	public static String PART_TOOL_BAR_REFRESH;
	public static String PART_TOOL_BAR_ADD;
	
	public static String PART_FUNCTION_REFRESH;
	public static String PART_FUNCTION_ADD;
	public static String PART_FUNCTION_UPDATE;
	public static String PART_FUNCTION_DEL;
	public static String PART_FUNCTION_SEARCH;
	public static String PART_FUNCTION_ADD_COMMIT;

	static {
		PART_ONE = "<link href=\"https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\"><script src=\"https://cdn.bootcss.com/layer/3.0.1/layer.min.js\"></script><style>.panel-body {padding: 0;}</style>";
		PART_TWO = "<script type=\"text/javascript\">{part_two_content}{part_two_function}</script>";
		
		PART_MAIN_READY = "$(document)"
			+".ready("
					+"function() {"
					+"{part_main_ready_toolbar}"
					+"$('#datagrid')"
								+".datagrid("
										+"{"
								
			+"title : '{part_main_ready_title}管理',"
			+"url : '/bg/{part_main_ready_url}/post',"
			+"toolbar : _toolbar,"
			+"columns : [ ["
			+"{part_main_ready_items}"
			+" ] ],"
											+"pagination : true,"
											+"rownumbers : true,"
											+"pageSize : 20,"
											+"rowStyler : function(index, row) {"
												+"return \"height:100px;\";"
												+"},"
											+"singleSelect : true"
											+"});"
						+"{part_main_ready_click}"

					+"});";
		
		PART_MAIN_READY_LIST_NORMAL = "{"
										+"field : '{part_main_ready_items_field}',"
										+"title : '{part_main_ready_items_title}',"
										+"width : {part_main_ready_items_width},"
										+"align : 'center'"
										+"}";
		PART_MAIN_READY_LIST_DATE = "{"
										+"field : '{part_main_ready_items_field}',"
										+"title : '{part_main_ready_items_title}',"
										+"width : {part_main_ready_items_width},"
										+"align : 'center',"
										+"formatter:function(value,row,index){"
										      +"return new Date(value).format('yyyy-MM-dd HH:mm:ss');"
										+"}"
									+"}";
		PART_MAIN_READY_LIST_BOOLEAN = "{"
											+"field : '{part_main_ready_items_field}',"
											+"title : '{part_main_ready_items_title}',"
											+"width : {part_main_ready_items_width},"
											+"align : 'center',"
											+"formatter : function(value, row,index) {"
												+"var a = '<img src=\"/images/ico_status_1.gif\"/>';"
												+"if (value == \"0\") {"
												+"a = '<img src=\"/images/ico_status_0.gif\"/>';"
												+"}"
												+"return a;"
											+"}"
										+"},";
		PART_MAIN_READY_LIST_ACTION = "{"
										+"field : 'action',"
										+"title : '操作',"
										+"width : 150,"
										+"align : 'center',"
										+"formatter : function(value, row,index) {"
												+"var a = \"<a href='javascript:;' class='updateBtn' data-id='\"+row.id+\"'><i class='fa fa-edit fa-2x' style='color:#888;'></i></a> \";"
												+"var b = \"<a href='javascript:;' class='delBtn' data-id='\"+row.id+\"'><i class='fa fa-trash-o fa-2x' style='color:#888;'></i></a> \";"
															+"return {part_main_ready_items_action}"
										+"}"
										+"}";
			
		
		PART_DATE_TYPE = "Date.prototype.format = function(fmt) {" + "var o = {" + "\"M+\" : this.getMonth() + 1, "
				+ "\"d+\" : this.getDate(),  " + "\"h+\" : this.getHours(),  " + "\"m+\" : this.getMinutes(), "
				+ "\"s+\" : this.getSeconds(), " + "\"q+\" : Math.floor((this.getMonth() + 3) / 3),  "
				+ "\"S\" : this.getMilliseconds() " + "};" + "if (/(y+)/.test(fmt))"
				+ "fmt = fmt.replace(RegExp.$1, (this.getFullYear() + \"\")" + ".substr(4 - RegExp.$1.length));"
				+ "for ( var k in o)" + "if (new RegExp(\"(\" + k + \")\").test(fmt))"
				+ "fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])"
				+ ": ((\"00\" + o[k]).substr((\"\" + o[k]).length)));" + "return fmt;" + "}";

		PART_TOOL_BAR_MAIN = "var _toolbar = [{part_tool_bar_content}];";

		PART_TOOL_BAR_CONNECT = ",'-',";
		
		PART_TOOL_BAR_REFRESH = "{" + "id : 'btnRefresh'," + "text : '刷新'," + "iconCls : 'icon-reload',"
				+ "handler : function() {" + "refresh();" + "}" + "}";
		
		PART_TOOL_BAR_ADD = "{" + "id : 'btnAddItem'," + "iconCls : 'icon-add'," + "text : '添加',"
				+ "handler : function() {" + "add();" + "}" + "}";
		
		PART_FUNCTION_REFRESH = "/* 刷新 */"
				+"function refresh() {"
					+"$('#datagrid').datagrid('reload');"
				+"}";
		
		PART_FUNCTION_ADD = "/* 添加 */"
				+"function add() {"
					+"$(\"#showAddId\").hide();"
					+"$(\"#myModalLabel\").text(\"新增\");"
					+"{PART_FUNCTION_ADD_ITEMS}"
					+"$(\"#myModal\").modal(\"show\");"
				+"}";
		
		PART_FUNCTION_UPDATE = "/* 更新 */"
			+"function update() {"
				+"var id = $(this).data(\"id\");"
				+"$(\"#myModalLabel\").text(\"修改\");"
				+"$.post(\"/bg/{part_main_ready_url}/get\", {id : id}, function(data) {"
				+"if (data.result == \"success\") {"
					+"{PART_FUNCTION_UPDATE_ITEMS}"
				+"} else {"
						+"alert(data.message);"
						+"}"
						+"});"
				+"$(\"#showAddId\").show();"
				+"$(\"#myModal\").modal(\"show\");"
				+"}";

		PART_FUNCTION_DEL = "/* 删除 */ "
			+ "function deleteItem(){"
		        +"var id = $(this).data(\"id\");"
		        +"if(!window.confirm(\"确认删除\")){"
		        +" return;"
		        +"}"
		        +"$.post(\"/bg/{part_main_ready_url}/delete\",{id:id},function(data){"
		        +"if (data.result == \"success\") {"
		        +"layer.msg(\"删除完成\");"
		        +"refresh();"
		        +"} else {"
		                +"alert(data.message);"
		                +"}"
		                +"})"
		    +"}";
		
		PART_FUNCTION_ADD_COMMIT = "/* 添加修改提交 */"
			+"function addSubmit() {"
				+"var req_params = {};"
				+"{PART_FUNCTION_COMMIT_ITEMS}"
				+"$.post('/bg/{part_main_ready_url}/add', req_params, function(data) {"
					+"if (data.result == \"success\") {"
						+"var title = $(\"#myModalLabel\").text();"
						+"layer.msg(title + \"完成\");"
						+"$(\"#myModal\").modal(\"hide\");"
						+"refresh();"
					+"} else {"
					+"alert(data.message);"
					+"}"
				+"});"
			+"}";
		
		PART_FUNCTION_SEARCH = "/* 搜索 */"
				+ "	function search(){"
					        +"{PART_FUNCTION_SEARCH_ITEM1}"
				        +"$('#datagrid').datagrid('load', {"
				            +"{PART_FUNCTION_SEARCH_ITEM2}"
				        +"});"
					+"}";
	}
	
	
}

class Item {
	private String beanName;
	private String realName;
	private int width;
	private int type;// 1:String;2:Date;3:boolean

	private int isShow;// 1:show;0:hidden
	private int isSearch;// 1:search;0:no search

	public Item(String beanName, String realName, int width, int type, int isShow, int isSearch) {
		super();
		this.beanName = beanName;
		this.realName = realName;
		this.width = width;
		this.type = type;
		this.isShow = isShow;
		this.isSearch = isSearch;
	}

	public String getBeanName() {
		return beanName;
	}

	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getIsShow() {
		return isShow;
	}

	public void setIsShow(int isShow) {
		this.isShow = isShow;
	}

	public int getIsSearch() {
		return isSearch;
	}

	public void setIsSearch(int isSearch) {
		this.isSearch = isSearch;
	}

}

class Core {

	private int doAdd;// 0/1
	private int doUpdate;// 0/1
	private int doDel;// 0/1

	private String lag;// 标识
	private String lagCN;
	

	public Core(int doAdd, int doUpdate, int doDel, String lag, String lagCN) {
		super();
		this.doAdd = doAdd;
		this.doUpdate = doUpdate;
		this.doDel = doDel;
		this.lag = lag;
		this.lagCN = lagCN;
	}

	public int getDoAdd() {
		return doAdd;
	}

	public void setDoAdd(int doAdd) {
		this.doAdd = doAdd;
	}

	public int getDoUpdate() {
		return doUpdate;
	}

	public void setDoUpdate(int doUpdate) {
		this.doUpdate = doUpdate;
	}

	public int getDoDel() {
		return doDel;
	}

	public void setDoDel(int doDel) {
		this.doDel = doDel;
	}

	public String getLag() {
		return lag;
	}

	public void setLag(String lag) {
		this.lag = lag;
	}

	public String getLagCN() {
		return lagCN;
	}

	public void setLagCN(String lagCN) {
		this.lagCN = lagCN;
	}

}
